/*
 * Copyright (c) 2019. Mikes. All rights reserved.
 *
 * You can contact me with sending email to bWlrZXNfMjAxMkAxNjMuY29t for more information!
 */

package com.climber.android.ui

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.view.WindowManager
import androidx.core.app.ActivityCompat
import androidx.lifecycle.Lifecycle
import com.alibaba.android.arouter.launcher.ARouter
import com.climber.android.R
import com.climber.android.commonres.app.AppAccount
import com.climber.android.commonsdk.app.AppConstants
import com.climber.android.commonsdk.app.AppEnv
import com.climber.android.commonsdk.app.AppFormStorage
import com.climber.android.commonres.ui.BaseMVPActivity
import com.climber.android.commonres.ui.dialog.CommonVerticalActionsDialog
import com.climber.android.commonsdk.util.WebLinkClickSpan
import com.climber.android.commonsdk.arouter.ARouterPathConstants
import com.climber.android.commonsdk.helper.openActivity
import io.ganguo.library.mvp.Config
import io.ganguo.library.mvp.ui.mvp.IPresenter
import io.ganguo.library.mvp.ui.mvp.di.component.AppComponent
import io.ganguo.library.mvp.util.RxLifecycleUtils
import io.ganguo.library.mvp.util.SpanUtils
import io.ganguo.library.mvp.util.UIUtils
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import java.util.concurrent.TimeUnit

/**
 * Created by Mikes at 2019-11-04 15:05
 */
class SplashActivity : BaseMVPActivity<IPresenter>() {
    override fun setupActivityComponent(appComponent: AppComponent) {
    }

    override fun getLayoutResourceId(): Int = 0

    override fun initView() {
    }

    override fun initListener() {
    }

    override fun initData() {
    }

    override fun changeStatusColor(): Boolean = false

    override fun onCreate(savedInstanceState: Bundle?) {
        setContentView(R.layout.app_activity_splash)
        super.onCreate(savedInstanceState)

        fullP()

        hideNavigationBar()

        // Fix `Android应用第一次安装成功后Home键切到后台再点击桌面图标应用重启`
        if (intent.flags and Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT != 0) {
            finish()
            return
        }

        //启动页窗口背景保持2s
        Observable.just(1)
            .delay(2, TimeUnit.SECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .`as`(RxLifecycleUtils.bindUntilEvent(this, Lifecycle.Event.ON_DESTROY))
            .subscribe({
                checkShowPrivacyDialog{ argee ->
                    if(argee){
                        checkAllPermissions {
                            checkShouldShowWelcomePage()
                        }
                    } else{
                        this@SplashActivity.finish()
                    }
                }
            }, {
                //none
                checkShowPrivacyDialog{ argee ->
                    if(argee){
                        checkAllPermissions {
                            checkShouldShowWelcomePage()
                        }
                    } else{
                        this@SplashActivity.finish()
                    }
                }
            })
    }

    /**
     * 9.0全屏,兼容水滴屏
     *
     */
    private fun fullP() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            val lp = window.attributes
            lp.layoutInDisplayCutoutMode =
                WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
            window.attributes = lp
        }
    }

    private fun hideNavigationBar() {
        //SYSTEM_UI_FLAG_FULLSCREEN 全屏时，状态栏被隐藏
        //SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN 全屏时，布局不会占用状态栏
        //SYSTEM_UI_FLAG_FULLSCREEN or SYSTEM_UI_FLAG_LAYOUT_STABLE 状态栏隐藏，再出现时，不会重新计算布局
        //SYSTEM_UI_FLAG_HIDE_NAVIGATION 导航栏不显示，布局延伸到导航栏
        //SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION 导航栏显示，布局延伸到导航栏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            val decorView = window.decorView
            val option =
                View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            decorView.systemUiVisibility = option
            window.navigationBarColor = Color.TRANSPARENT
        } else {
            val decorView = window.decorView
            val uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_FULLSCREEN
            decorView.systemUiVisibility = uiOptions
        }
    }

    private fun checkShowPrivacyDialog(completion: (Boolean) -> Unit){
        if(AppFormStorage.showIfAfterInstalled()){
            Config.putBoolean(AppConstants.CONFIG_LAUNCH_AFTER_INSTALLED, false)

            CommonVerticalActionsDialog.generate {
                setTitle("服务协议和隐私政策")

                setContent(SpanUtils()
                    .append("请您务必审慎阅读、充分理解\"服务协议\"和\"隐私政策\"各条款，包括但不限于：为了向您提供即时通讯、内容分享等服务，我们需要收集您的设备信息、操作日志等个人信息。")
                    .append("\n\n您可阅读")
                    .append("《服务协议》")
                    .setForegroundColor(UIUtils.getColor(R.color.common_green))
                    .setClickSpan(WebLinkClickSpan(AppEnv.USER_AGREEMENT_URL, preferTitle = "服务协议"))
                    .append("和")
                    .append("《隐私政策》")
                    .setForegroundColor(UIUtils.getColor(R.color.common_green))
                    .setClickSpan(WebLinkClickSpan(AppEnv.USER_AGREEMENT_URL, preferTitle = "隐私政策"))
                    .append("了解详细信息。如您同意，请点击\"同意\"开始接受我们的服务。")
                    .create())
                setContentGravity(Gravity.LEFT)

                setDialogCancelable(false)

                setConfirmBtnLabel("同意") {
                    completion(true)
                }

                setCancelBtnLabel("不同意并退出") {
                    completion(false)
                }

                create()
            }.show(supportFragmentManager, "")
        } else{
            completion(true)
        }
    }

    private fun checkAllPermissions(completion: (() -> Unit)) {
        if(ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
        ){
            completion()
            return
        }

        requestSinglePermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, "") {
            requestSinglePermission(Manifest.permission.READ_PHONE_STATE, "") {
                requestSinglePermission(Manifest.permission.ACCESS_FINE_LOCATION, "") {
                    completion()
                }
            }
        }
    }

    private fun checkShouldShowWelcomePage() {
//        if (AppFormStorage.shouldShowWelcomePage()) {
//            this.openActivityForResult(Intent(this, WelcomeActivity::class.java), 100)
//        } else {
            dismissSplashAndOpenHomepage()
//        }
    }

    private fun dismissSplashAndOpenHomepage() {
        /**
         * 切换为非全屏，解决全屏启动页跳转到包含状态栏主题的首页时，顶部状态栏白色闪烁问题。
         */
        window.setFlags(
            WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN
        )

        this.openActivity(Intent(this, MaterialMainActivity::class.java)
                        .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK)
        )
        this.finish()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 100 && resultCode == Activity.RESULT_OK) {
            dismissSplashAndOpenHomepage()
        }
    }
}